package demo.huodongbaoming.service.impl;

import demo.huodongbaoming.entity.ActivityCategory;
import demo.huodongbaoming.repository.ActivityCategoryRepository;
import demo.huodongbaoming.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private ActivityCategoryRepository categoryRepository;

    @Override
    @Transactional
    public ActivityCategory createCategory(String name, String description) {
        ActivityCategory category = new ActivityCategory();
        category.setName(name);
        category.setDescription(description);
        return categoryRepository.save(category);
    }

    @Override
    public ActivityCategory getCategoryById(Long id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("类别不存在"));
    }

    @Override
    public List<ActivityCategory> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    @Transactional
    public ActivityCategory updateCategory(Long id, String name, String description) {
        ActivityCategory category = getCategoryById(id);
        category.setName(name);
        category.setDescription(description);
        return categoryRepository.save(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Long id) {
        ActivityCategory category = getCategoryById(id);
        categoryRepository.delete(category);
    }
} 